import React, {useState, useEffect} from 'react';
import {Card, Typography, Spin, Input, Button, Flex, Space} from 'antd';
import {LeftOutlined, ScanOutlined} from '@ant-design/icons';
import styles from '../style.less';

const {Title, Text} = Typography;

interface QRCodePaymentProps {
  paymentMethod: string;
  amount: number;
  loading: boolean;
  onPay: (scannedCode: string) => Promise<void>; // 修改为返回Promise的异步函数
  onBack: () => void;
}

const QRCodePayment: React.FC<QRCodePaymentProps> = ({
                                                       paymentMethod,
                                                       amount,
                                                       loading,
                                                       onPay,
                                                       onBack,
                                                     }) => {
  const isWechat = paymentMethod === 'wechat';
  const paymentAppName = isWechat ? '微信' : '支付宝';
  const [scannedCode, setScannedCode] = useState<string>('');
  const [isProcessing, setIsProcessing] = useState(false);

  const handlePayment = async () => {
    setIsProcessing(true);
    try {
      await onPay(scannedCode);
    } finally {
      setIsProcessing(false);
      setScannedCode('');
    }
  };

  // 模拟扫码枪输入（实际项目应监听硬件事件）
  useEffect(() => {
    const handleKeyPress = async (e: KeyboardEvent) => {
      if (e.key === 'Enter' && scannedCode) {
        await handlePayment();
      } else if (/^\d$/.test(e.key)) {
        setScannedCode(prev => prev + e.key);
      }
    };

    window.addEventListener('keypress', handleKeyPress);
    return () => window.removeEventListener('keypress', handleKeyPress);
  }, [scannedCode]);

  return (
    <div className={styles.qrCodePayment}>
      <Card zIndex={2000}>
        <div className={styles.headerContainer}>
          <Button
            type="text"
            icon={<LeftOutlined/>}
            onClick={onBack}
            className={styles.backButton}
          >
            返回支付方式
          </Button>

          <div className={styles.paymentHeader}>
            <Title level={4} className={styles.paymentTitle}>
              {paymentAppName}扫码支付
            </Title>
            <Text strong className={styles.paymentAmount}>
              应付金额: <span className={styles.amount}>¥{amount.toFixed(2)}</span>
            </Text>
          </div>
        </div>

        <div className={styles.scanContainer}>
          {isProcessing ? (
            <Spin
              size="large"
              tip="支付处理中..."
              className={styles.spinContainer}
            />
          ) : (
            <div className={styles.scanInputWrapper}>
              <Input
                prefix={<ScanOutlined style={{color: '#1890ff'}}/>}
                placeholder="等待扫码枪输入..."
                value={scannedCode}
                readOnly
                disabled
                className={styles.scanInput}
              />
              <Text type="secondary" className={styles.scanTip}>
                {scannedCode
                  ? '检测到付款码，自动处理中...'
                  : `请使用扫码枪扫描客户的${paymentAppName}付款码`}
              </Text>
            </div>
          )}
        </div>
        <Flex justify={"center"} gap={"middle"}>
          <Button type={'primary'} onClick={async () => {
            setScannedCode('')
          }}>重新扫描</Button>
          <Button type={'primary'} onClick={async () => {
            await handlePayment()
          }}>测试支付</Button>
        </Flex>
        <div className={styles.paymentTips}>
          <Text type="secondary">
            扫码成功后系统将自动完成收款
          </Text>
        </div>
      </Card>
    </div>
  );
};

export default QRCodePayment;
